package com.enjoyor.soa.traffic.frame.support.help;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileHelper {

    public static void main(String[] args) {
        try {
            String a = FileHelper.readFile("G://temp/eva.mp4", "GBK");
            System.out.println(a);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 将文本文件中的内容读入到buffer中
     *
     * @param buffer
     *            buffer
     * @param filePath
     *            文件路径
     * @throws IOException
     *             异常
     * @author cn.outofmemory
     * @date 2013-1-7
     */
    public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {
        InputStream is = new FileInputStream(filePath);
        String line; // 用来保存每行读取的内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        line = reader.readLine(); // 读取第一行
        while (line != null) { // 如果 line 为空说明读完了
            buffer.append(line); // 将读到的内容添加到 buffer 中
            buffer.append("\n"); // 添加换行符
            line = reader.readLine(); // 读取下一行
        }
        reader.close();
        is.close();
    }

    /**
     * 将文本文件中的内容读入到buffer中,带编码
     *
     * @param buffer
     *            buffer
     * @param filePath
     *            文件路径
     * @throws IOException
     *             异常
     * @author cn.outofmemory
     * @date 2013-1-7
     */
    public static void readToBuffer(StringBuffer buffer, String filePath, String code) throws IOException {
        InputStream is = new FileInputStream(filePath);
        String line; // 用来保存每行读取的内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, code));
        line = reader.readLine(); // 读取第一行
        while (line != null) { // 如果 line 为空说明读完了
            buffer.append(line); // 将读到的内容添加到 buffer 中
            buffer.append("\n"); // 添加换行符
            line = reader.readLine(); // 读取下一行
        }
        reader.close();
        is.close();
    }

    /**
     * 读取文本文件内容
     *
     * @param filePath
     *            文件所在路径
     * @return 文本内容
     * @throws IOException
     *             异常
     * @author cn.outofmemory
     * @date 2013-1-7
     */
    public static String readFile(String filePath) throws IOException {
        StringBuffer sb = new StringBuffer();
        FileHelper.readToBuffer(sb, filePath);
        return sb.toString();
    }

    /**
     * 读取文本文件内容，带编码
     * 
     * @param filePath
     * @param code
     * @return
     * @throws IOException
     */
    public static String readFile(String filePath, String code) throws IOException {
        StringBuffer sb = new StringBuffer();
        FileHelper.readToBuffer(sb, filePath, code);
        return sb.toString();
    }

    public static boolean creatFile(String dirName) {
        try {
            File file = new File(dirName);
            if (!file.exists())
                return file.mkdir();
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    // 删除文件
    public static boolean delete(String fileName) {
        boolean flag = false;
        File file = new File(fileName);
        if (!file.exists()) {
            System.out.println("删除文件失败:" + fileName + "不存在！");
            flag = false;
        } else {
            if (file.isFile())
                flag = deleteFile(fileName);
            else
                flag = false;
            // return deleteDirectory(fileName);
        }
        return flag;
    }

    /**
     * 删除单个文件
     *
     * @param fileName
     *            要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                // System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    /**
     * 批量下载图片并打包成zip
     *
     * @param file
     * @param response
     */
    public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String downloadFilename,
            List<String> files) {
        try {
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");// 转换中文否则可能会产生乱码
            response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            for (int i = 0; i < files.size(); i++) {
                try {
                    if (files.get(i).contains("jpg")) {
                        URL url = new URL(files.get(i));
                        String[] temp = files.get(i).split("/");
                        zos.putNextEntry(new ZipEntry(temp[temp.length - 1].split(".jpg")[0] + ".jpg"));
                        // FileInputStream fis = new FileInputStream(new
                        // File(files[i]));
                        InputStream fis = url.openConnection().getInputStream();
                        byte[] buffer = new byte[1024];
                        int r = 0;
                        while ((r = fis.read(buffer)) != -1) {
                            zos.write(buffer, 0, r);
                        }
                        fis.close();
                    } else {
                        URL url = new URL(files.get(i));
                        String[] temp = files.get(i).split("/");
                        zos.putNextEntry(new ZipEntry(temp[temp.length - 1]));
                        // FileInputStream fis = new FileInputStream(new
                        // File(files[i]));
                        InputStream fis = url.openConnection().getInputStream();
                        byte[] buffer = new byte[1024];
                        int r = 0;
                        while ((r = fis.read(buffer)) != -1) {
                            zos.write(buffer, 0, r);
                        }
                        fis.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            zos.flush();
            zos.close();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 读取某个文件夹下的所有文件
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List<Map<String, String>> readfileDirectory(String filepath) {
        List<Map<String, String>> list = new ArrayList();
        File file = new File(filepath);
        if (!file.isDirectory()) {

        } else if (file.isDirectory()) {
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                // File readfile = new File(filepath + "\\" + filelist[i]);
                // if (!readfile.isDirectory()) {
                Map<String, String> map = new HashMap();
                map.put("path", filepath + "\\" + filelist[i]);
                map.put("name", filelist[i]);
                list.add(map);

                /*
                 * } else if (readfile.isDirectory()) { List<File> childList =
                 * readfileDirectory(filepath + "\\" + filelist[i]); for(File
                 * child:childList){ list.add(child); } childList = null; }
                 */
            }

        }
        return list;
    }

    /**
     * 读取某个文件夹下的所有文件
     * 
     * @param filepath
     *            读取目录
     * @param maxLength
     *            一次读取最大的文件量
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List<Map<String, String>> readfileDirectory(String filepath, int maxLength) {
        List<Map<String, String>> list = new ArrayList();
        File file = new File(filepath);
        if (!file.isDirectory()) {

        } else if (file.isDirectory()) {
            String[] filelist = file.list();
            int length = filelist.length > maxLength ? maxLength : filelist.length;
            for (int i = 0; i < length; i++) {
                // File readfile = new File(filepath + "\\" + filelist[i]);
                // if (!readfile.isDirectory()) {
                Map<String, String> map = new HashMap();
                map.put("path", filepath + "\\" + filelist[i]);
                map.put("name", filelist[i]);
                list.add(map);

                // }
            }

        }
        return list;
    }

}
